<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="100px"
      class="formWrapper"
      labelPosition="left"
    >
      <el-form-item label="logo图片">
        <img-upload v-model="form.logo" :previewStyle="{width: '100px', height: '100px'}"></img-upload>
      </el-form-item>
      <el-form-item label="排序权重">
        <el-col :span="12">
          <el-input-number v-model="form.sorts"></el-input-number>
        </el-col>
        <el-col :span="12">
          <p class="tips">数值越大越靠前</p>
        </el-col>
      </el-form-item>
      <el-form-item
        v-for="(input, key) in inputs"
        :key="key"
        :label="input"
        :prop="key"
      >
        <el-input v-model="form[key]"></el-input>
      </el-form-item>
      <el-form-item label="最快放款时间">
        <el-select v-model="form.fastTime" :class="$style.selectItem">
          <el-option
            v-for="(date, index) in dateOptions"
            :key="date"
            :label="date"
            :value="index + 1"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="贷款期限">
        <el-col :span="11">
          <el-select v-model="form.loanLimitMin" :class="$style.select">
            <el-option
              v-for="(date, index) in dateOptions"
              :key="date"
              :label="date"
              :value="index + 1"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col class="h-line" :span="2">-</el-col>
        <el-col :span="11">
          <el-select v-model="form.loanLimitMax" :class="$style.select">
            <el-option
              v-for="(date, index) in dateOptions"
              :key="date"
              :label="date"
              :value="index + 1"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="还款方式">
        <el-select v-model="form.repayType" :class="$style.selectItem">
          <el-option
            v-for="(item, index) in repayTypeOptions"
            :key="item"
            :label="item"
            :value="index + 1"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="贷款范围(元)">
        <el-col :span="11">
          <el-input v-model="form.loanRangeMin"></el-input>
        </el-col>
        <el-col class="h-line" :span="2">-</el-col>
        <el-col :span="11">
          <el-input v-model="form.loanRangeMax"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="热门产品">
        <el-switch
          v-model="form.isHot"
          on-text="是"
          off-text="否"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="是否有信用卡">
        <el-switch
          v-model="form.reditCard"
          on-text="有"
          off-text="无"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
          :key="tag"
          v-for="tag in tags"
          :closable="true"
          :close-transition="false"
          @close="handleClose(tag)"
          :class="$style.tag"
          type="primary"
        >
        {{tag}}
        </el-tag>
        <el-input
          :class="$style.newTagInput"
          v-if="tagInputVisible"
          v-model="tagInputValue"
          size="mini"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else size="small" @click="showTagInput">+ 新标签</el-button>
      </el-form-item>
      <el-form-item label="成功率" prop="succRate">
        <el-rate
          v-model="form.succRate"
          text-color="#ff9900"
          allow-half
        >
        </el-rate>
      </el-form-item>
      <el-form-item label="办理流程">
        <img-upload v-model="form.proImg"></img-upload>
      </el-form-item>
      <el-form-item label="申请条件">
        <el-input type="textarea" v-model="form.conditions" :rows="5"></el-input>
      </el-form-item>
      <el-form-item label="所需材料">
        <el-input type="textarea" v-model="form.material" :rows="5"></el-input>
      </el-form-item>
      <hr>
      <el-button type="primary" class="long-btn" @click="save">保 存</el-button>
    </el-form>
    <el-dialog title="素材库" :visible.sync="dialogVisible" size="large">
      <gallery :openInDialog="true" v-model="selectedImgs"></gallery>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ImgUpload } from 'components'
import product from 'config/product'
import Gallery from 'views/Material/Gallery'
import * as apis from 'services/products'

const checkSuccRate = (rule, value, callback) => {
  if (isNaN(value)) {
    callback(new Error('成功率只能是数字'))
  } else {
    callback()
  }
}

const inputs = {
  linkUrl: '跳转链接',
  name: '产品名称',
  applyNum: '申请人数',
  rate: '利率',
}

function createRequiredRule(inputs) {
  const ret = {}
  for (const key in inputs) {
    if ({}.hasOwnProperty.call(inputs, key)) {
      ret[key] = [{
        required: true, message: `请输入${inputs[key]}`, trigger: 'blur',
      }]
    }
  }
  return ret
}

export default {
  name: 'LoanProductEdit',
  components: {
    ImgUpload,
    Gallery,
  },
  data() {
    return {
      inputs,
      form: {
        linkUrl: '',
        name: '',
        logo: '',
        applyNum: '',
        rate: '',
        conditions: '',
        material: '',
        succRate: 5,
        reditCard: false,
        fastTime: '',
        // loanLimit: '',
        loanLimitMin: '',
        loanLimitMax: '',
        loanRangeMin: '',
        loanRangeMax: '',
        proImg: '',
        repayType: '',
        isHot: false,
      },
      tagInputValue: '',
      tagInputVisible: false,
      dialogVisible: false,
      tags: [],
      selectedImgs: [],
      rules: {
        ...createRequiredRule(inputs),
        succRate: [
          { required: true, message: '请输入成功率', trigger: 'blur' },
          { validator: checkSuccRate },
        ],
      },
      dateOptions: product.dateOptions,
      repayTypeOptions: product.repayTypeOptions,
    }
  },
  created() {
    const { id } = this.$route.query
    if (id) {
      this.id = id
      this.getProductById(id)
    }
  },
  methods: {
    async getProductById(id) {
      const data = await apis.getProductById(id)
      const separator = str => str.split('|')
      this.form = Object.assign({}, data)
      this.form.applyNum = data.applyNum.toString()
      this.form.isHot = !!data.isHot
      this.form.reditCard = !!data.reditCard
      this.selectedImgs = separator(data.proImg)
      this.tags = data.tags.length ? separator(data.tags) : []
    },
    handleInputConfirm() {
      const tagInputValue = this.tagInputValue
      if (tagInputValue) {
        this.tags.push(tagInputValue)
      }
      this.inputVisible = false
      this.tagInputValue = ''
    },
    handleClose(tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
    },
    showTagInput() {
      this.tagInputVisible = true
    },
    openDialog() {
      this.dialogVisible = true
    },
    closeDialog() {
      this.dialogVisible = false
    },
    save() {
      const payload = {
        linkUrl: this.form.linkUrl,
        name: this.form.name,
        logo: this.form.logo,
        applyNum: this.form.applyNum,
        rate: this.form.rate,
        conditions: this.form.conditions,
        material: this.form.material,
        succRate: this.form.succRate,
        fastTime: this.form.fastTime,
        loanRangeMin: this.form.loanRangeMin,
        loanRangeMax: this.form.loanRangeMax,
        loanLimitMin: this.form.loanLimitMin,
        loanLimitMax: this.form.loanLimitMax,
        proImg: this.form.proImg,
        sorts: this.form.sorts,
        repayType: this.form.repayType,
        tags: this.tags.join('|'),
        isHot: this.form.isHot ? 1 : 0,
        reditCard: this.form.reditCard ? 1 : 0,
      }

      if (this.id) {
        payload.id = this.id
      }

      apis.saveProducts(payload)
        .then(() => {
          this.$message({
            type: 'success',
            message: '保存成功!',
          })
          this.$router.push('/loanProduct')
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '保存失败',
          })
        })
    },
  },
}
</script>

<style module>
.newTagInput {
  width: 60px;
}

.tag {
  margin-right: 12px;
}

.preview {
  margin: 20px 0;
  width: 800px;
}

.preview > img {
  margin-right: 12px;
  max-width: 300px;
  vertical-align: top;
}

.select {
  width: 100%;
}

.selectItem {
  width: 46%;
}
</style>
